package com.wang.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class UDPServer {

	/*
	 * UDP是一种面向非连接的传输层协议,在正式通信前不必与对方建立连接,因此它的通信效率极高,但可靠性不如TCP.
	 *  因此UDP适用于一次只传送少量数据、对可靠性要求不高 的环境.(关于UDP协议的详细介绍也可参考的博客TCP/IP入门(3) –传输层).
	 */
		
	private static final byte[] RECEIVE_BUFFER = new byte[1024]; 
	
	public static void main(String[] args) {
		
		try{
			DatagramSocket socket = new DatagramSocket(8088);			
			DatagramPacket gram = new DatagramPacket(RECEIVE_BUFFER,RECEIVE_BUFFER.length);
			while(true){
				socket.receive(gram);
				String receiveContent = new String(gram.getData(),0,gram.getLength());
				System.out.println(String.format("client IP:%s, Port:%s, reveiveContent:%s", gram.getAddress(),gram.getPort(),receiveContent));
				String resp = String.format("hello %s", receiveContent);
				socket.send(new DatagramPacket(resp.getBytes(), resp.length(), gram.getAddress(),gram.getPort()));				
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{			
		}
		
		
		
		
		
	}
}
